<template>
  <div class="goods-params">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item to="/goods">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="mt_20px">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        effect="dark"
        show-icon
      ></el-alert>

      <div class="my_20px">
        <span>选择商品分类：</span>
        <!-- v-model="msg" 就是 :value="msg" 和 @input="msg = $event" 的组合 -->
        <goods-cate-cascader
          v-model="goodsCate"
          :allow-checked-levels="[3]"
          @change="getList(true)"
        ></goods-cate-cascader>
      </div>

      <el-tabs type="border-card" v-model="sel" @tab-click="onClickTab">
        <el-tab-pane
          :label="`动态参数（${manyList.loaded ? '已加载' : '未加载'}）`"
          name="many"
        >
          <div>
            <el-button type="primary" size="mini" :disabled="cat_id === 0"
              >添加参数</el-button
            >
          </div>
          <el-table :data="manyList" border stripe class="mt_20px">
            <el-table-column type="expand">
              <template #default="{ row }">
                <tag-list
                  :list="row.attr_val_arr"
                  @del="onDelAttrVal(row, $event)"
                  @add="onAddAttrVal(row, $event)"
                ></tag-list>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template #default>
                <el-button type="primary" icon="el-icon-edit" size="mini"
                  >修改</el-button
                >
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane
          :label="`静态属性（${onlyList.loaded ? '已加载' : '未加载'}）`"
          name="only"
        >
          <div>
            <el-button type="primary" size="mini" :disabled="cat_id === 0"
              >添加属性</el-button
            >
          </div>
          <el-table :data="onlyList" border stripe class="mt_20px">
            <el-table-column type="expand">
              <template #default="{ row }">
                <tag-list
                  :list="row.attr_val_arr"
                  @del="onDelAttrVal(row, $event)"
                  @add="onAddAttrVal(row, $event)"
                ></tag-list>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template #default>
                <el-button type="primary" icon="el-icon-edit" size="mini"
                  >修改</el-button
                >
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
// @ --> /src
import GoodsCateCascader from '@/components/GoodsCateCascader.vue';
import TagList from '@/components/TagList.vue';
export default {
  name: 'GoodsParams',
  components: { GoodsCateCascader, TagList },
  data() {
    return {
      sel: 'many',
      goodsCate: [],
      manyList: [], // 动态参数列表数据
      onlyList: [], // 静态属性列表数据
    };
  },
  computed: {
    // 分类id
    cat_id() {
      const len = this.goodsCate.length;
      if (len > 0) {
        return this.goodsCate[len - 1];
      }
      return 0;
    },
  },
  methods: {
    async onAddAttrVal(row, value) {
      // eslint-disable-next-line
      const attr_vals = row.attr_vals + `,${value}`;
      const { data: res } = await this.__apis.goodsParams.edit({
        cat_id: row.cat_id,
        attr_id: row.attr_id,
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals,
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      // eslint-disable-next-line
      row.attr_vals = attr_vals;
      row.attr_val_arr = attr_vals.split(',');
      this.$message.success('添加成功');
    },
    async onDelAttrVal(row, indexOfDel) {
      // eslint-disable-next-line
      const attr_vals = row.attr_val_arr
        .filter((v, i) => i !== indexOfDel)
        .join(',');

      const { data: res } = await this.__apis.goodsParams.edit({
        cat_id: row.cat_id,
        attr_id: row.attr_id,
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals,
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      // eslint-disable-next-line
      row.attr_vals = attr_vals;
      row.attr_val_arr.splice(indexOfDel, 1);
      this.$message.success('删除成功');
    },
    async getList(isChangeGoodsCate = false) {
      if (isChangeGoodsCate) {
        // 如果是改变了商品分类，那么就清空列表数据
        this.manyList = [];
        this.onlyList = [];
      }
      if (this.cat_id === 0) {
        return;
      }
      const { data: res } = await this.__apis.goodsParams.list({
        cat_id: this.cat_id,
        sel: this.sel,
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      // 用来标记数据是否已加载
      res.data.loaded = true;

      res.data.forEach((v) => {
        // 给响应数据的对象中都添加一个新的属性attr_val_arr，用来存储attr_vals分隔的数组
        if (v.attr_vals.trim() === '') {
          v.attr_val_arr = [];
        } else {
          v.attr_val_arr = v.attr_vals.split(',');
        }
      });
      if (this.sel === 'many') {
        this.manyList = res.data;
      } else if (this.sel === 'only') {
        this.onlyList = res.data;
      }
    },
    onClickTab() {
      if (
        (this.sel === 'many' && !this.manyList.loaded) ||
        (this.sel === 'only' && !this.onlyList.loaded)
      ) {
        this.getList();
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
